import React, { useState, useEffect, useCallback } from 'react';
import { Card, Button, message } from 'antd';
import { ReloadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn';

import FilterBar from './components/FilterBar';
import ScanTaskTable from './components/ScanTaskTable';
import TaskDetailModal from './components/TaskDetailModal';

import { fetchScanTaskList, deleteScanTask } from '../../../services/scanTask';
import type { 
  ScanTaskInfo, 
  ScanTaskQueryParams, 
  PageResult 
} from './types';

// 配置dayjs
dayjs.extend(relativeTime);
dayjs.locale('zh-cn');

interface ScanRecordsProps {
  unitId: string;
}

const ScanRecords: React.FC<ScanRecordsProps> = ({ unitId }) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<PageResult<ScanTaskInfo>>({
    records: [],
    total: 0,
    size: 10,
    current: 1,
    pages: 0
  });
  const [queryParams, setQueryParams] = useState<ScanTaskQueryParams>({
    unitId,
    pageNum: 1,
    pageSize: 10,
    orderBy: 'start_time',
    orderDirection: 'DESC'
  });
  
  // 弹窗相关状态
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedTask, setSelectedTask] = useState<ScanTaskInfo | null>(null);

  // 加载扫描任务列表
  const loadScanTasks = useCallback(async (params: ScanTaskQueryParams = queryParams) => {
    setLoading(true);
    try {
      const result = await fetchScanTaskList(params);
      setData(result);
    } catch (error) {
      console.error('加载扫描任务失败:', error);
      message.error('加载扫描任务失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  }, [queryParams]);

  // 页面初始化加载
  useEffect(() => {
    if (unitId) {
      loadScanTasks();
    }
  }, [unitId, loadScanTasks]);

  // 处理筛选
  const handleFilter = (filterParams: ScanTaskQueryParams) => {
    const newParams = {
      ...queryParams,
      ...filterParams,
      unitId, // 确保unitId不变
      pageNum: 1 // 重置到第一页
    };
    setQueryParams(newParams);
    loadScanTasks(newParams);
  };

  // 处理重置筛选
  const handleResetFilter = () => {
    const defaultParams = {
      unitId,
      pageNum: 1,
      pageSize: queryParams.pageSize,
      orderBy: 'start_time',
      orderDirection: 'DESC'
    };
    setQueryParams(defaultParams);
    loadScanTasks(defaultParams);
  };

  // 处理分页
  const handlePageChange = (page: number, pageSize: number) => {
    const newParams = {
      ...queryParams,
      pageNum: page,
      pageSize
    };
    setQueryParams(newParams);
    loadScanTasks(newParams);
  };

  // 查看详情
  const handleViewDetail = (task: ScanTaskInfo) => {
    setSelectedTask(task);
    setDetailModalVisible(true);
  };

  // 删除扫描任务
  const handleDelete = async (unitTaskId: number) => {
    try {
      await deleteScanTask(unitTaskId);
      message.success('删除成功');
      // 重新加载当前页数据
      loadScanTasks();
    } catch (error) {
      console.error('删除扫描任务失败:', error);
      message.error('删除失败，请稍后重试');
    }
  };

  // 手动刷新
  const handleRefresh = () => {
    loadScanTasks();
  };

  return (
    <div style={{ padding: '0 24px' }}>
      {/* 页面标题和操作按钮 */}
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        marginBottom: '24px',
        padding: '16px 24px',
        background: 'linear-gradient(135deg, #722ed1 0%, #9c36f5 100%)',
        borderRadius: '12px',
        boxShadow: '0 4px 20px rgba(114, 46, 209, 0.3)'
      }}>
        <div>
          <h2 style={{ 
            color: '#fff', 
            margin: 0, 
            fontSize: '24px',
            fontWeight: 'bold'
          }}>
            📋 扫描记录
          </h2>
          <p style={{ 
            color: 'rgba(255,255,255,0.8)', 
            margin: '8px 0 0 0',
            fontSize: '14px'
          }}>
            查看单元的扫描任务执行历史和详细结果
          </p>
        </div>
        <Button
          type="primary"
          icon={<ReloadOutlined />}
          onClick={handleRefresh}
          loading={loading}
          style={{
            background: 'rgba(255,255,255,0.2)',
            border: 'none',
            color: '#fff',
            borderRadius: '8px'
          }}
        >
          刷新数据
        </Button>
      </div>

      <Card>
        {/* 筛选栏 */}
        <FilterBar
          onFilter={handleFilter}
          onReset={handleResetFilter}
          loading={loading}
        />

        {/* 扫描任务表格 */}
        <ScanTaskTable
          data={data}
          loading={loading}
          onViewDetail={handleViewDetail}
          onDelete={handleDelete}
          onPageChange={handlePageChange}
        />
      </Card>

      {/* 任务详情弹窗 */}
      <TaskDetailModal
        visible={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setSelectedTask(null);
        }}
        scanTask={selectedTask}
      />
    </div>
  );
};

export default ScanRecords;